package cn.myplus.uc.user

import org.springframework.hateoas.CollectionModel
import org.springframework.hateoas.server.mvc.RepresentationModelAssemblerSupport
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn
import org.springframework.stereotype.Component

/**
 * @project myplus5
 * @description 用户实体与模型转换
 * @author libo
 * @date 2023-10-03 18:06:58
 */
@Component
class UserModelAssembler :
    RepresentationModelAssemblerSupport<User, UserModel>(UserController::class.java, UserModel::class.java) {
    override fun toModel(entity: User): UserModel {
        val userModel: UserModel = instantiateModel(entity)
        userModel.add(linkTo(methodOn(UserController::class.java).getUser(entity.id)).withSelfRel())
        userModel.id = entity.id
        userModel.name = entity.name
        userModel.loginName = entity.loginName
        userModel.phone = entity.phone

        return userModel;
    }

    override fun toCollectionModel(entities: MutableIterable<User>): CollectionModel<UserModel> {
        val userModels: CollectionModel<UserModel> = super.toCollectionModel(entities)

//        userModels.forEach { userModel: UserModel ->
//            userModel.add(linkTo(methodOn(UserController::class.java).getUser(userModel.id)).withSelfRel())
//        }

        userModels.add(methodOn(UserController::class.java).getUsers(null)?.let { linkTo(it).withSelfRel() })

        return userModels
    }

}